﻿using System;
using System.Collections.Generic;
using System.Text;
using LP580.CG;
using System.Data;

namespace LP580.CG
{
    /// <summary>
    /// clsGiftProductClass 的摘要说明
    /// </summary>
    public class clsGiftProductClass
    {
        #region 构造函数

        public clsGiftProductClass() { }

        public clsGiftProductClass(int prmGiftProductClassID)
        {
            clsGiftProductClass entity = clsGiftProductClass.GetByKey(prmGiftProductClassID);
            this._giftproductclassid = entity._giftproductclassid;
            this._userid = entity._userid;
            this._giftproductclassname = entity._giftproductclassname;
            this._giftproductclasscode = entity._giftproductclasscode;
            this._giftproductupclassname = entity._giftproductupclassname;
            this._giftproductupclassid = entity._giftproductupclassid;
            this._giftproductcount = entity._giftproductcount;
        }

        public static clsGiftProductClass GetByKey(int prmGiftProductClassID)
        {
            clsGiftProductClass entity = new clsGiftProductClass();
            DBase dbo = new DBase();
            IDataReader dr = dbo.ExecuteReader("SELECT * FROM [tbl_GiftProductClass] WHERE GiftProductClassID=" + prmGiftProductClassID.ToString());
            if (dr.Read())
            {
                entity = DrToClass(dr);
            }
            dr.Dispose();
            dr = null;
            dbo.CloseConn();
            dbo = null;
            return entity;
        }

        public static clsGiftProductClass GetByCode(string prmGiftProductClassCode)
        {
            clsGiftProductClass entity = new clsGiftProductClass();
            DBase dbo = new DBase();
            IDataReader dr = dbo.ExecuteReader("SELECT * FROM [tbl_GiftProductClass] WHERE GiftProductClassCode='" + prmGiftProductClassCode + "'");
            if (dr.Read())
            {
                entity = DrToClass(dr);
            }
            dr.Dispose();
            dr = null;
            dbo.CloseConn();
            dbo = null;
            return entity;
        }

        private static clsGiftProductClass DrToClass(System.Data.IDataReader dr)
        {
            clsGiftProductClass entity = new clsGiftProductClass();

            int iTmp = 0;
            if (!int.TryParse(dr["GiftProductClassID"].ToString(), out iTmp))
                iTmp = 0;
            entity._giftproductclassid = iTmp;
            iTmp = 0;
            if (!int.TryParse(dr["UserID"].ToString(), out iTmp))
                iTmp = 0;
            entity._userid = iTmp;
            entity._giftproductclassname = dr["GiftProductClassName"].ToString();
            entity._giftproductclasscode = dr["GiftProductClassCode"].ToString();
            entity._giftproductupclassname = dr["GiftProductUpClassName"].ToString();
            iTmp = 0;
            if (!int.TryParse(dr["GiftProductUpClassID"].ToString(), out iTmp))
                iTmp = 0;
            entity._giftproductupclassid = iTmp;
            iTmp = 0;
            if (!int.TryParse(dr["GiftProductCount"].ToString(), out iTmp))
                iTmp = 0;
            entity._giftproductcount = iTmp;

            return entity;
        }

        #endregion

        public static bool MoveGoUp(clsGiftProductClass prmEntity)
        {
            return MoveGo(true, prmEntity);
        }

        public static bool MoveGoDown(clsGiftProductClass prmEntity)
        {
            return MoveGo(false, prmEntity);
        }

        private static bool MoveGo(bool isUp, clsGiftProductClass prmEntity)
        {
            bool ret = false;

            string code = prmEntity._giftproductclasscode;
            int codelen = code.Length;
            if (codelen == 0 || codelen % 4 != 0)
                return false;

            string strNB = new string('-', codelen);
            string strWhere = "";
            if (codelen > 4)
            {
                strWhere = string.Format("and left(GiftProductClassCode,{0})='{1}'", codelen - 4, code.Substring(0, codelen - 4));
            }
            string sql = "";
            if (isUp)
            {
                sql = string.Format("select top 1 GiftProductClassCode from tbl_GiftProductClass where len(GiftProductClassCode)={0} and GiftProductClassCode<'{1}' {2} order by GiftProductClassCode desc", codelen, code, strWhere);
            }
            else
            {
                sql = string.Format("select top 1 GiftProductClassCode from tbl_GiftProductClass where len(GiftProductClassCode)={0} and GiftProductClassCode>'{1}' {2} order by GiftProductClassCode asc", codelen, code, strWhere);
            }
            string strTmp = "";
            DBase dbo = new DBase();
            IDataReader dr = dbo.ExecuteReader(sql);
            if (dr.Read())
            {
                strTmp = dr[0].ToString();
            }
            dr.Dispose();
            dr = null;            

            if (strTmp != "" && (strTmp.Length % 4 == 0))
            {
                //移动上层栏目
                string MoveParentSQL = string.Format("Update tbl_GiftProductClass set GiftProductClassCode='{0}'+SUBSTRING(GiftProductClassCode,{1},len(GiftProductClassCode)) WHERE left(GiftProductClassCode,{2})='{3}'", strNB, codelen + 1, codelen, strTmp);

                dbo.ExecSql(MoveParentSQL);

                //更新目标栏目
                string UpdateTargetSQL = string.Format("Update tbl_GiftProductClass set GiftProductClassCode='{0}'+SUBSTRING(GiftProductClassCode,{1},len(GiftProductClassCode)) WHERE left(GiftProductClassCode,{2})='{3}'", strTmp, codelen + 1, codelen, code);

                dbo.ExecSql(UpdateTargetSQL);

                //更新上层栏目
                string UpdateParentSQL = string.Format("Update tbl_GiftProductClass set GiftProductClassCode='{0}'+SUBSTRING(GiftProductClassCode,{1},len(GiftProductClassCode)) WHERE left(GiftProductClassCode,{2})='{3}'", code, codelen + 1, codelen, strNB);

                dbo.ExecSql(UpdateParentSQL);

                ret = true;
            }

            dbo.CloseConn();
            dbo = null;

            return ret;
           
        }

        /// <summary>
        ///  处理产品增减对应
        ///  分类统计数量变化
        /// </summary>
        public void DealGiftProductCount(int s)
        {
            string sql = string.Format("UPDATE [tbl_GiftProductClass] SET GiftProductCount=GiftProductCount+{0} WHERE (GiftProductClassCode = LEFT('{1}', LEN(GiftProductClassCode)))", s, this._giftproductclasscode);
            DBase dbo = new DBase();
            dbo.ExecSql(sql);
            dbo.CloseConn();
            dbo = null;
        }

        /// <summary>
        /// 新增了一个产品
        /// </summary>
        public void AddGiftProduct()
        {
            DealGiftProductCount(1);
        }

        /// <summary>
        /// 删除了一个产品
        /// </summary>
        public void DecGiftProduct()
        {
            DealGiftProductCount(-1);
        }

        #region 增删改数据库操作

        /// <summary>
        /// 数据库插入操作
        /// </summary>
        /// <param name="prmEntity"></param>
        /// <returns></returns>
        private static int doInsert(clsGiftProductClass prmEntity)
        {
            DataTableManage SaveDTM = new DataTableManage();
            string sql;
            sql = string.Format("insert into [tbl_GiftProductClass](" +
                            " [UserID]," +
                            " [GiftProductClassName]," +
                            " [GiftProductClassCode]," +
                            " [GiftProductUpClassName]," +
                            " [GiftProductUpClassID]," +
                            " [GiftProductCount]" +
            ") values (" +
                    "@UserID," +
                    "@GiftProductClassName," +
                    "@GiftProductClassCode," +
                    "@GiftProductUpClassName," +
                    "@GiftProductUpClassID," +
                    "@GiftProductCount" +
            ")");
            SaveDTM.Sql = sql;
            SaveDTM.AddNewParam("@UserID", prmEntity._userid);
            SaveDTM.AddNewParam("@GiftProductClassName", prmEntity._giftproductclassname);
            SaveDTM.AddNewParam("@GiftProductClassCode", prmEntity._giftproductclasscode);
            SaveDTM.AddNewParam("@GiftProductUpClassName", prmEntity._giftproductupclassname);
            SaveDTM.AddNewParam("@GiftProductUpClassID", prmEntity._giftproductupclassid);
            SaveDTM.AddNewParam("@GiftProductCount", prmEntity._giftproductcount);
            SaveDTM.Insert();
            return 1;
        }

        public static int Insert(clsGiftProductClass prmEntity, int parentid)
        {
            clsGiftProductClass parentcls = clsGiftProductClass.GetByKey(parentid);
            string parentcode = parentcls.GiftProductClassCode;

            prmEntity.GiftProductClassCode = GetNextCode(parentcode);

            /**** 是否需要？？ ****/
            prmEntity.GiftProductUpClassID = parentcls.GiftProductClassID;
            prmEntity.GiftProductUpClassName = parentcls.GiftProductClassName;
            /*********************/

            return clsGiftProductClass.doInsert(prmEntity);
        }

        private static string GetNextCode(string parentcode)
        {
            string nextcode = "";
            int iCode = 0;
            DBase dbo = new DBase();
            string sql = string.Format("SELECT TOP 1 GiftProductClassCode FROM [tbl_GiftProductClass] WHERE GiftProductClassCode LIKE '{0}____' ORDER BY GiftProductClassCode DESC", parentcode);
            IDataReader dr = dbo.ExecuteReader(sql);
            if (dr.Read())
            {
                iCode = Convert.ToInt32(dr["GiftProductClassCode"].ToString().Substring(parentcode.Length)) + 1;
                nextcode = "000" + iCode.ToString();
                nextcode = nextcode.Substring(nextcode.Length - 4);
                nextcode = parentcode + nextcode;
            }
            else
            {
                nextcode = parentcode + "0001";
            }
            dr.Dispose();
            dr = null;
            dbo.CloseConn();
            dbo = null;

            return nextcode;
        }

        public static int Insert(clsGiftProductClass prmEntity, string parentcode)
        {
            clsGiftProductClass parentcls = clsGiftProductClass.GetByCode(parentcode);

            return clsGiftProductClass.Insert(prmEntity, parentcls.GiftProductClassID);
        }

        public static bool Delete(int prmGiftProductClassID)
        {
            return clsGiftProductClass.Delete(new clsGiftProductClass(prmGiftProductClassID));
        }
        public static bool Delete(clsGiftProductClass prmEntity)
        {
            if (!prmEntity.HasChild)
            {
                DBase dbo = new DBase();
                dbo.ExecSql("DELETE FROM [tbl_GiftProductClass] WHERE GiftProductClassID=" + prmEntity._giftproductclassid.ToString());
                dbo.CloseConn();
                dbo = null;
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 数据库更新操作
        /// </summary>
        /// <param name="prmEntity"></param>
        /// <returns></returns>
        private static bool doUpdate(clsGiftProductClass prmEntity)
        {
            DataTableManage SaveDTM = new DataTableManage();
            string sql;
            sql = "UPDATE [tbl_GiftProductClass] SET " +
                "[UserID] = @UserID, " +
                "[GiftProductClassName] = @GiftProductClassName, " +
                "[GiftProductClassCode] = @GiftProductClassCode, " +
                "[GiftProductUpClassName] = @GiftProductUpClassName, " +
                "[GiftProductUpClassID] = @GiftProductUpClassID, " +
                "[GiftProductCount] = @GiftProductCount " +
            " WHERE GiftProductClassID=@GiftProductClassID";
            SaveDTM.Sql = sql;
            SaveDTM.AddNewParam("@UserID", prmEntity._userid);
            SaveDTM.AddNewParam("@GiftProductClassName", prmEntity._giftproductclassname);
            SaveDTM.AddNewParam("@GiftProductClassCode", prmEntity._giftproductclasscode);
            SaveDTM.AddNewParam("@GiftProductUpClassName", prmEntity._giftproductupclassname);
            SaveDTM.AddNewParam("@GiftProductUpClassID", prmEntity._giftproductupclassid);
            SaveDTM.AddNewParam("@GiftProductCount", prmEntity._giftproductcount);
            SaveDTM.AddNewParam("@GiftProductClassID", prmEntity._giftproductclassid);
            SaveDTM.Update();
            return true;
        }

        public static bool Update(clsGiftProductClass prmEntity, int parentid)
        {
            string now_code = prmEntity.GiftProductClassCode;

            clsGiftProductClass parentcls = clsGiftProductClass.GetByKey(parentid);
            string parentcode = parentcls.GiftProductClassCode;

            if (parentcode != now_code.Substring(0, now_code.Length - 4))
            {
                string new_code = "";

                new_code = GetNextCode(parentcode);

                //更新与之有关的变动编码
                doUpdateCode(now_code, new_code);

                prmEntity.GiftProductClassCode = new_code;

                /**** 是否需要？？ ****/
                prmEntity.GiftProductUpClassID = parentcls.GiftProductClassID;
                prmEntity.GiftProductUpClassName = parentcls.GiftProductClassName;
                /*********************/

            }

            return doUpdate(prmEntity);
        }

        /// <summary>
        /// 更新有关的变动编码
        /// </summary>
        /// <param name="now_code"></param>
        /// <param name="new_code"></param>
        private static void doUpdateCode(string now_code, string new_code)
        {
            DataTableManage SaveDTM = new DataTableManage();
            string sql = "Update [tbl_GiftProductClass] set GiftProductClassCode='" + new_code + "'+Right(GiftProductClassCode,Len(GiftProductClassCode)-" + now_code.Length + ") where GiftProductClassCode like '%" + now_code + "%'";
            SaveDTM.Sql = sql;
            SaveDTM.Update();
        }

        #endregion

        #region 获取集合

        public static List<clsGiftProductClass> GetCollection()
        {
            return GetCollection("");
        }

        public static List<clsGiftProductClass> GetCollection(string where)
        {
            List<clsGiftProductClass> ls = new List<clsGiftProductClass>();
            DBase dbo = new DBase();
            string sql = string.Format("SELECT * FROM [tbl_GiftProductClass] {0} ORDER BY GiftProductClassCode ASC", where);
            IDataReader dr = dbo.ExecuteReader(sql);
            while (dr.Read())
            {
                ls.Add(DrToClass(dr));
            }
            dr.Dispose();
            dr = null;
            dbo.CloseConn();
            dbo = null;
            return ls;
        }

        /// <summary>
        /// 取得子类，不含孙子节点
        /// </summary>
        /// <returns></returns>
        public List<clsGiftProductClass> GetDirectChildCollection()
        {
            return GetChildCollection(1);
        }

        /// <summary>
        /// 取得子类，含孙子节点
        /// </summary>
        /// <returns></returns>
        public List<clsGiftProductClass> GetChildCollection()
        {
            List<clsGiftProductClass> ls = new List<clsGiftProductClass>();
            DBase dbo = new DBase();
            string sql = "";
            if (this._giftproductclasscode == "")
            {
                sql = "SELECT * FROM [tbl_GiftProductClass] ORDER BY GiftProductClassCode ASC";
            }
            else
            {
                sql = string.Format("SELECT * FROM [tbl_GiftProductClass] WHERE GiftProductClassCode LIKE '{0}%' ORDER BY GiftProductClassCode ASC", this._giftproductclasscode);
            }
            IDataReader dr = dbo.ExecuteReader(sql);
            while (dr.Read())
            {
                ls.Add(DrToClass(dr));
            }
            dr.Dispose();
            dr = null;
            dbo.CloseConn();
            dbo = null;

            return ls;
        }

        /// <summary>
        /// 取得相对层级的子类
        /// </summary>
        /// <param name="level">相对本类的层数</param>
        /// <returns></returns>
        public List<clsGiftProductClass> GetChildCollection(int level)
        {
            List<clsGiftProductClass> ls = new List<clsGiftProductClass>();
            DBase dbo = new DBase();
            string sql = string.Format("SELECT * FROM [tbl_GiftProductClass] WHERE GiftProductClassCode LIKE '{0}' ORDER BY GiftProductClassCode ASC", this._giftproductclasscode + new string('_', level * 4));
            IDataReader dr = dbo.ExecuteReader(sql);
            while (dr.Read())
            {
                ls.Add(DrToClass(dr));
            }
            dr.Dispose();
            dr = null;
            dbo.CloseConn();
            dbo = null;

            return ls;
        }

        /// <summary>
        ///  取得根类
        /// </summary>
        /// <returns></returns>
        public clsGiftProductClass GetRoot()
        {
            clsGiftProductClass cls = new clsGiftProductClass();
            if (this._giftproductclasscode.Length >= 4)
            {
                DBase dbo = new DBase();
                string sql = string.Format("SELECT * FROM [tbl_GiftProductClass]  WHERE (GiftProductClassCode = '{0}') ", this._giftproductclasscode.Substring(0, 4));
                IDataReader dr = dbo.ExecuteReader(sql);
                if (dr.Read())
                {
                    cls = DrToClass(dr);
                }
                dr.Dispose();
                dr = null;
                dbo.CloseConn();
                dbo = null;
            }
            return cls;
        }

        /// <summary>
        ///  取得父类
        /// </summary>
        /// <returns></returns>
        public List<clsGiftProductClass> GetParentCollection()
        {
            List<clsGiftProductClass> ls = new List<clsGiftProductClass>();
            DBase dbo = new DBase();
            string sql = string.Format("SELECT * FROM [tbl_GiftProductClass]  WHERE (GiftProductClassCode = LEFT('{0}', LEN(GiftProductClassCode))) ORDER BY GiftProductClassCode ", this._giftproductclasscode);
            IDataReader dr = dbo.ExecuteReader(sql);
            while (dr.Read())
            {
                ls.Add(DrToClass(dr));
            }
            dr.Dispose();
            dr = null;
            dbo.CloseConn();
            dbo = null;
            return ls;
        }
        /// <summary>
        /// 根据id值获取类别代码
        /// </summary>
        public static List<int> GetCodeById(int id)
        {
            DBase db = new DBase();
            string code = db.ExecuteScalar("select GiftProductClassCode from tbl_GiftProductClass where GiftProductClassID=" + id.ToString()).ToString();
            db = new DBase();
            string sql = string.Format("SELECT GiftProductClassID FROM [tbl_GiftProductClass]  WHERE (GiftProductClassCode = LEFT('{0}', LEN(GiftProductClassCode))) ORDER BY GiftProductClassCode ", code);
            IDataReader dr = db.ExecuteReader(sql);
            List<int> ls = new List<int>();
            while (dr.Read())
            {
                ls.Add(Convert.ToInt16(dr[0]));
            }
            dr.Dispose();
            dr = null;
            db.CloseConn();
            db = null;
            return ls;
        }
        #endregion

        #region 字段属性

        private int _giftproductclassid = 0;
        public int GiftProductClassID
        {
            get { return _giftproductclassid; }
            set { _giftproductclassid = value; }
        }

        private int _userid = 0;
        /// <summary>
        /// 所属用户,如为0则为管理设置
        /// </summary>
        public int UserID
        {
            get { return _userid; }
            set { _userid = value; }
        }

        private string _giftproductclassname = "";
        /// <summary>
        /// 类别名称
        /// </summary>
        public string GiftProductClassName
        {
            get { return _giftproductclassname; }
            set { _giftproductclassname = value; }
        }

        private string _giftproductclasscode = "";
        /// <summary>
        /// 类别代码
        /// </summary>
        public string GiftProductClassCode
        {
            get { return _giftproductclasscode; }
            set { _giftproductclasscode = value; }
        }

        private string _giftproductupclassname = "";
        public string GiftProductUpClassName
        {
            get { return _giftproductupclassname; }
            set { _giftproductupclassname = value; }
        }

        private int _giftproductupclassid = 0;
        public int GiftProductUpClassID
        {
            get { return _giftproductupclassid; }
            set { _giftproductupclassid = value; }
        }

        private int _giftproductcount = 0;
        public int GiftProductCount
        {
            get { return _giftproductcount; }
            set { _giftproductcount = value; }
        }

        /// <summary>
        /// 分类所在第几层
        /// </summary>
        public int GiftProductClassLevel
        {
            get { return this._giftproductclasscode.Length/4; }
        }

        /// <summary>
        /// 路径全名，格式如：
        ///    父节点-子节点-叶节点
        /// </summary>
        public string FullPathName
        {
            get
            {
                string tmp = "";
                DBase dbo = new DBase();
                string sql = "SELECT GiftProductClassName FROM [tbl_GiftProductClass] WHERE (GiftProductClassCode = LEFT('" + this._giftproductclasscode + "', LEN(GiftProductClassCode))) ORDER BY GiftProductClassCode ";
                IDataReader dr = dbo.ExecuteReader(sql);
                while (dr.Read())
                {
                    tmp += dr[0].ToString() + "-";
                }
                dr.Dispose();
                dr = null;
                dbo.CloseConn();
                dbo = null;
                if (tmp.Length > 0)
                    tmp = tmp.Substring(0, tmp.Length - 1);

                return tmp;
            }
        }

        /// <summary>
        /// 是否有子节点
        /// </summary>
        public bool HasChild
        {
            get
            {
                bool v = false;
                DBase dbo = new DBase();
                string sql = string.Format("SELECT TOP 1 GiftProductClassID FROM [tbl_GiftProductClass] where GiftProductClassCode like '{0}____' ORDER BY GiftProductClassID DESC", this._giftproductclasscode);
                IDataReader dr = dbo.ExecuteReader(sql);
                v = dr.Read();
                dr.Dispose();
                dr = null;
                dbo.CloseConn();
                dbo = null;
                return v;
            }
        }

        /// <summary>
        /// 简单树状文本显示的名称
        /// </summary>
        public string TreeName
        {
            get
            {
                string tmp = "";
                int Level;
                if (this._giftproductclasscode != "")
                {
                    Level = (this._giftproductclasscode.Length / 4 - 1) * 2;

                    if (this._giftproductclasscode.Length > 4) tmp += "├";
                    for (int i = 0; i < Level; i++) tmp += "－";
                }
                tmp += this._giftproductclassname;
                return tmp;
            }
        }


        public clsGiftProductClass Parent
        {
            get
            {
                clsGiftProductClass cls = new clsGiftProductClass();
                int len = this._giftproductclasscode.Length;
                if (len > 4)
                {
                    string code = this._giftproductclasscode.Substring(0, len - 4);
                    cls = GetByCode(code);
                    if (cls._giftproductclassid == 0) cls = null;
                }
                else
                {
                    cls = null;
                }
                return cls;
            }
        }

        #endregion
    }
}
